import React from "react"
import { message, Modal, Table, Form, Button, Select, Input, Radio} from 'antd'
import {
    fetchTableListApi,
    fileListApi,
    removeFieldInfoApi,
    modifyFieldInfoApi,
    fetchFileInfoApi,
    modifyFileInfoApi,
    addFieldInfoApi,
    fetchTableAndColumnsApi
} from "../api/projectConfig"
import * as Constants from "../utils/Constants"
import {Config} from "../utils/Constants";

const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

class VoDomain extends React.Component {


    editDataMap = {};
    projectId;
    fileId;
    state = {
        tableColumns: [],
        voFields: [],
        tableList: [],

        dataTypeMap: {}, // table row edit

        voList:[],

        /** form data */
        comment: '',
        superId: 0,
        paradigm: 'no',
        name: '',
        id: 0,
        fileType:''

    };

    constructor(props) {
        super(props);
        this.projectId = this.props.projectId

    }

    componentDidMount() {

        fetchTableListApi(this.projectId, 'vo').then(res=>{
            let _list = res.data.data;
            _list = _list ? _list : [];
            this.setState({...this.state, tableList: _list});
        });

        this.fileId = this.props.fileNode.fileId;
        fetchFileInfoApi(this.fileId).then(res=>{

            let data = res.data.data;
            let {id, name, superId, comment, paradigm, fileType} = data;

            this.changeSuperSelected(superId);

            this.setState({...this.state, voFields: data.fields, id, name, superId, comment, paradigm, fileType})
        });

        let voRet = fileListApi(this.props.projectId, 'vo');
        voRet.then((res) =>{
            this.state.voList = res.data.data
        });
    }

    changeSuperSelected = (value) => {
        if(value > 0) {
            fetchTableAndColumnsApi(value).then(res=>{
                this.setState({...this.state, tableColumns: res.data.data.columns})
            })
        } else {
            this.setState({...this.state, tableColumns: []})
        }
    };

    saveFileInfo = () => {

        let formData = this.props.form.getFieldsValue();
        let {name, comment, paradigm, superId} = formData;
        let postData = {id: this.fileId, name, comment, paradigm, superId};
        modifyFileInfoApi(postData).then(res=>{
            message.success('保存成功！')
        })
    };


    getDataPathByType = (id, dType)=> {

        var type = this.state.dataTypeMap['k_' + id];
        type = type ? type : dType;

        if(! type || type === 'base') {
            return Constants.Config.DATA_TYPE_LIST
        } else if(type === 'T') {

            return ['T']
        } else if(type === 'vo') {
            return this.state.voList
        }
    };

    editDataChange = (record, key, value, index) => {

        let k = 'k_' + record.id;
        let obj = this.editDataMap[k];
        if( ! obj ) {
            obj = {}
        }

        if(key === 'dataType') {

            let _voFields = this.state.voFields;
            var _oraginTypePath = obj['typePath'];
            var _oraginTypeKey = obj['typeKey'];

            var _newTypePath = '';
            var _newTypeKey = '';
            // 原来的值有修改 typePath typeKey
            if(value === 'T') {
                _newTypePath = 'T';
                _newTypeKey = 'T';
            } else if(value === 'vo') {
                _newTypePath = this.state.voList[0].name;
                _newTypeKey = this.state.voList[0].id;
            } else if(value === 'base') {
                _newTypePath = Constants.Config.DATA_TYPE_LIST[0];
                _newTypeKey = Constants.Config.DATA_TYPE_LIST[0];
            }


            console.info('_newTypePath=' + _newTypePath + ',_newTypeKey=' + _newTypeKey + ',value=' + value);


            if(_oraginTypePath != _newTypePath || _oraginTypeKey != _newTypeKey) {
                _voFields[index].typePath = _newTypePath;
                _voFields[index].typeKey = _newTypeKey;

                obj['typePath'] = _newTypePath;
                obj['typeKey'] = _newTypeKey;

                this.setState({...this.state, voFields: _voFields});
            }
        }

        obj[key] = value;
        this.editDataMap[k] = obj
    }

    saveRowData = (record, index) => {

        var that = this;
        var obj = this.editDataMap['k_' + record.id];
        if(obj) {
            if( ! record.empty) {
                obj['id'] = record.id;
                modifyFieldInfoApi(obj).then((res)=>{
                    message.success('保存成功！')
                })
            } else {
                obj.fileId = this.fileId;
                addFieldInfoApi(obj).then((res)=>{
                    that.state.voFields[index] = res.data.data
                    delete that.state.voFields[index].empty
                    message.success('添加成功！')
                })
            }
        }
    }

    removeFieldInfo = (record) => {
        var that = this
        confirm({
            title: '是否确定删除?',
            content: '点击确定将删除',
            onOk() {
                // TODO 册除表行

                that.state.voFields.splice(that.state.voFields.findIndex(item => item.id === record.id), 1);
                that.setState({...that.state, voFields: that.state.voFields});

                removeFieldInfoApi(record.id).then(res=>{
                    message.success('岫除成功！')
                })
            },
            onCancel() {
                console.log('Cancel');
            },
        });

    }


    addVoField = ()=>{

        var _voFields = this.state.voFields;

        console.info(JSON.stringify(_voFields))

        if(_voFields.length > 0) {
            if(_voFields[0].empty) {
                return;
            }
        }
        _voFields.splice(0,0,{empty: true, id: Math.random()});
        this.setState({...this.state, voFields: _voFields});
    }

    render() {


        var ignoreVo = Config.VO_IGNORE.indexOf(this.state.name) > -1;

        const tableFieldColumns = [{
            title: 'name',
            dataIndex: 'name',
            key: 'name',
        }, {
            title: 'db type',
            dataIndex: 'mysqlType',
            key: 'type',
        }, {
            width: '60%',
            title: 'comment',
            dataIndex: 'comment',
            key: 'comment',
        }];


        const voPropertyColumns = [
            {
                title: 'name',
                key: 'name',
                render: (text, record, index) => (
                    <Input defaultValue={record.name} onChange={(e) =>{
                        this.editDataChange(record, 'name', e.target.value, index)
                    }} />
                )
            }, {
                title: 'comment',
                key: 'comment',
                render: (text, record, index) => (
                    <Input defaultValue={record.comment} onChange={(e) =>{
                        this.editDataChange(record, 'comment', e.target.value, index)
                    }} />
                )
            }, {
                title: '对象类型',
                key: 'dataType',
                render: (text, record, index) => (
                    <Radio.Group defaultValue={record.dataType} onChange={(e)=>{
                        this.editDataChange(record, 'dataType', e.target.value, index);
                        let key = 'k_'+record.id;
                        this.state.dataTypeMap[key] = e.target.value;
                        this.setState({dataTypeMap: this.state.dataTypeMap})
                    }}>
                        <Radio.Button value="base">base</Radio.Button>
                        <Radio.Button value="vo">vo</Radio.Button>
                        <Radio.Button value="T">T</Radio.Button>
                    </Radio.Group>
                ),
            }, {
                title: '数据类型',
                key: 'typePath',
                render: (text, record, index) => (
                    <select defaultValue={record.typeKey} onChange={(e) =>{
                        let value = e.target.value
                        this.editDataChange(record, 'typeKey', e.target.value, index);

                        var typePath = value;
                        if(value > 0) {
                            let newArray = this.state.voList.filter(item => item.id == value);
                            typePath = newArray[0].name
                        }
                        this.editDataChange(record, 'typePath', typePath)

                    }} >
                        {this.getDataPathByType(record.id, record.dataType).map((value, index)=>
                            <option value={typeof value === 'object' ? value.id : value} key={index}>{typeof value === 'object' ? value.name : value}</option>
                        )}
                    </select>
                )
            }, {
                title: '集合类型',
                key: 'collectionType',
                render: (text, record, index) => (
                    <Radio.Group defaultValue={record.collectionType} onChange={(e) =>{
                        this.editDataChange(record, 'collectionType', e.target.value, index)
                    }}>
                        <Radio.Button value="single">single</Radio.Button>
                        <Radio.Button value="list">list</Radio.Button>
                        <Radio.Button value="set">set</Radio.Button>
                        <Radio.Button value="map">map</Radio.Button>
                    </Radio.Group>
                ),
            }, {
                title: '操作',
                key: 'operation',
                render: (text, record, index) => (
                    ignoreVo ? '' :
                    <span>
                        <Button type="primary" size='small' onClick={()=>{
                            this.saveRowData(record, index)
                        }}>save</Button>&nbsp;
                        <Button type="danger" size='small' onClick={()=>{
                            this.removeFieldInfo(record)
                        }}>del</Button>
                    </span>
                ),
            }
        ]


        const formItemLayout = {
            labelCol: {
                xs: { span: 12 },
                sm: { span: 3 },
            },
            wrapperCol: {
                xs: { span: 12 },
                sm: { span: 10 },
            },
        }
        const { getFieldDecorator } = this.props.form



        console.info('ignoreVo=' + ignoreVo + ',name=' + this.state.name)

        return (
            <div>
                <span className="code_key">package</span>
                <Form className="form_item_4" onSubmit={this.saveFileInfo}>

                    <FormItem {...formItemLayout} label="类注释" >
                        {getFieldDecorator('comment', {
                            initialValue: this.state.comment,
                            rules: [{ required: true, message: 'Please input your note!' }],
                        })(
                            <TextArea />
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="extend table" >
                        {getFieldDecorator('superId', {
                            initialValue: this.state.superId
                        })(
                            <Select onChange={this.changeSuperSelected}>
                                <Option value={0}>无</Option>
                                {this.state.tableList.map((tab, index) => <Option value={tab.id} key={tab.id}>{tab.name}</Option>)}
                            </Select>
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="Class Name" >
                        {getFieldDecorator('name', {
                            initialValue: this.state.name,
                            rules: [{ required: true, message: 'Please input your note!' }],
                        })(
                            <Input />
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="是否范型" >
                        {getFieldDecorator('paradigm', {
                            initialValue: this.state.paradigm
                        })(
                            <Radio.Group >
                                <Radio value="no">否</Radio>
                                <Radio value="yes">是</Radio>
                            </Radio.Group>
                        )}
                    </FormItem>

                    <Button type="primary" onClick={this.saveFileInfo} style={{position: "absolute", right: "20px", top: "60px", display: ignoreVo?'none':''}}>保存</Button>
                </Form>
                <hr />
                <h3>table</h3>
                <Table rowKey={record => record.id} className={'table-columns-tab'} dataSource={this.state.tableColumns} columns={tableFieldColumns} pagination={false} />
                <hr />

                <Button style={{display: ignoreVo?'none':''}} type="primary" size='small' onClick={this.addVoField}>添加VO字段</Button>
                <hr />
                <Table rowKey={record => record.id} className={'table-columns-tab'} dataSource={this.state.voFields} columns={voPropertyColumns} pagination={false} />

            </div>
        )
    }
}


const _VoDomain = Form.create()(VoDomain)
export default _VoDomain